package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.master.ActivityModule;
import cn.com.connext.scrm.domain.master.ActivityModuleConfig;
import cn.com.connext.scrm.domain.master.ActivityModuleConfigChild;
import cn.com.connext.scrm.domain.master.DrawActivity;
import cn.com.connext.scrm.repository.master.ActivityModuleConfigChildRepository;
import cn.com.connext.scrm.repository.master.ActivityModuleConfigRepository;
import cn.com.connext.scrm.repository.master.ActivityModuleRepository;
import cn.com.connext.scrm.repository.master.DrawActivityRepository;
import cn.com.connext.scrm.service.dto.ActivityModuleConfigDTO;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.web.rest.vm.ActivityModuleConfigAddVM;
import cn.com.connext.scrm.web.rest.vm.ActivityModuleConfigEditVM;
import cn.com.connext.scrm.web.rest.vm.ActivityModuleConfigVM;
import cn.com.connext.scrm.web.rest.vm.ActivityModuleVM;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
public class ActivityModuleConfigService {

    @Autowired
    private ActivityModuleConfigRepository amcRepository;
    @Autowired
    private ActivityModuleRepository amRepository;
    @Autowired
    private ActivityModuleConfigChildRepository amcchildRepository;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    public JsonResult save(ActivityModuleConfigAddVM vm) {
        JsonResult result =new JsonResult();
        if(vm !=null){
            List<ActivityModuleConfigVM> addList = vm.getAddList();
            if(addList !=null && addList.size() >0){
                ActivityModuleConfig ac= amcRepository.findOrderLimitOne();
                long b =0;
                if(ac != null && ac.getConfigOrder() != null){
                    b=ac.getConfigOrder();
                }
                List<ActivityModuleConfigChild> allList = new ArrayList<>();
                ActivityModuleConfig config = null;
                ActivityModuleConfigChild cl = null;
                DrawActivity activity = null;
                for (int i = 0; i < addList.size(); i++) {
                    //判断是修改还是新增
                    if(StringUtils.isNotBlank(addList.get(i).getComponentName())){
                        //ActivityModuleConfig byComponentName = amcRepository.findByComponentName(addList.get(i).getComponentName());
                        ActivityModuleConfig byComponentName = amcRepository.findByComponentNameAndType(addList.get(i).getComponentName(),addList.get(i).getType());
                        //兼容编辑，验证是否是编辑 不为编辑则抛出异常
                    if (null != byComponentName && null == addList.get(i).getId()) {
                        result.setState(-1);
                        result.setMessage("同一类型下组件名称不能重复!");
                        return result;
//                        throw new ServiceException("-1","同一类型下组件名称不能重复");
                    }
                    //活动新增处理
                    if ("1".equals(addList.get(i).getEditFlag())) {
                        /**
                         * 引入addActivityModuleList，进行组件配置新增
                         */
                        if(addList.get(i).getId() != null){
                            if(StringUtils.isNotEmpty(addList.get(i).getActivityId())){
                                //删除该活动原有组件关系
                                amRepository.deleteByActivityId(addList.get(i).getActivityId());
                            }
                            ActivityModule activityModule = new ActivityModule();
                            activityModule.setActivityId(addList.get(i).getActivityId());
                            activityModule.setActivityModuleConfigId(addList.get(i).getId());
                            long m =1;
                            activityModule.setModuleOrder(m);
                            amRepository.save(activityModule);
                        }
                        /**
                         * 210806 新增图片名称及按钮
                         */
                        if (StringUtils.isNotEmpty(addList.get(i).getActivityId())) {
                            activity = drawActivityRepository.findOne(addList.get(i).getActivityId());
                            if (StringUtils.isNotEmpty(addList.get(i).getButtonName())) {
                                activity.setButtonName(addList.get(i).getButtonName());
                            }
                            if (StringUtils.isNotEmpty(addList.get(i).getButtonImg())) {
                                activity.setButtonImg(addList.get(i).getButtonImg());
                            }
                            activity.setUpdateTime(new Date());
                            drawActivityRepository.saveAndFlush(activity);
                        }

                    } else {
                        //活动编辑处理

                        if (byComponentName != null){
                            config = amcRepository.findOne(byComponentName.getId());
                        } else {
                            config = new ActivityModuleConfig();
                        }
                        config.setType(addList.get(i).getType());
                        if(addList.get(i).getIsAutoLb() != null){
                            config.setIsAutoLb(addList.get(i).getIsAutoLb());
                        }

                        config.setComponentName(addList.get(i).getComponentName());
                        b +=1;
                        config.setConfigOrder(b);
                        ActivityModuleConfig entity = amcRepository.saveAndFlush(config);
                        List<ActivityModuleConfigChild> lbtList = addList.get(i).getLbtList();
                        cl = new ActivityModuleConfigChild();
                        if(StringUtils.isNotEmpty(addList.get(i).getUrl())){
                            cl.setUrl(addList.get(i).getUrl());
                            cl.setActivityModuleConfigId(entity.getId());
                            if(StringUtils.isNotEmpty(addList.get(i).getVideoImage())){
                                cl.setVideoImage(addList.get(i).getVideoImage());
                            }
                            allList.add(cl);
                        }else{
                            if(lbtList !=null && lbtList.size() >0){
                                for (ActivityModuleConfigChild child:lbtList) {
                                    child.setActivityModuleConfigId(entity.getId());
                                    child.setUrl(child.getUrl());
                                    allList.add(child);
                                }
                            }
                        }

                        /**
                         * 引入addActivityModuleList，进行组件配置新增
                         */
                        if(addList.get(i).getId() != null){
                            if(StringUtils.isNotEmpty(addList.get(i).getActivityId())){
                                //删除该活动原有组件关系
                                amRepository.deleteByActivityId(addList.get(i).getActivityId());
                            }
                            ActivityModule activityModule = new ActivityModule();
                            activityModule.setActivityId(addList.get(i).getActivityId());
                            activityModule.setActivityModuleConfigId(addList.get(i).getId());
                            long m =1;
                            activityModule.setModuleOrder(m);
                            amRepository.save(activityModule);
                        } else if (null != entity && null != entity.getId()) {
                            if(StringUtils.isNotEmpty(addList.get(i).getActivityId())){
                                //删除该活动原有组件关系
                                amRepository.deleteByActivityId(addList.get(i).getActivityId());
                            }
                            ActivityModule activityModule = new ActivityModule();
                            activityModule.setActivityId(addList.get(i).getActivityId());
                            activityModule.setActivityModuleConfigId(entity.getId());
                            long m =1;
                            activityModule.setModuleOrder(m);
                            amRepository.save(activityModule);
                        }
                        /**
                         * 210806 新增图片名称及按钮
                         */
                        if (StringUtils.isNotEmpty(addList.get(i).getActivityId())) {
                            activity = drawActivityRepository.findOne(addList.get(i).getActivityId());
                            if (StringUtils.isNotEmpty(addList.get(i).getButtonName())) {
                                activity.setButtonName(addList.get(i).getButtonName());
                            }
                            if (StringUtils.isNotEmpty(addList.get(i).getButtonImg())) {
                                activity.setButtonImg(addList.get(i).getButtonImg());
                            }
                            activity.setUpdateTime(new Date());
                            drawActivityRepository.saveAndFlush(activity);
                        }


                    }


//                    else {
////                        config = new ActivityModuleConfig();
//                    }
//                    config.setType(addList.get(i).getType());
//                    if(addList.get(i).getIsAutoLb() != null){
//                        config.setIsAutoLb(addList.get(i).getIsAutoLb());
//                    }
//
//                    config.setComponentName(addList.get(i).getComponentName());
//                    b +=1;
//                    config.setConfigOrder(b);
                    /**
                     * 210806 新增图片名称及按钮
                     */
//                    if (StringUtils.isNotEmpty(addList.get(i).getActivityId())) {
//                        activity = drawActivityRepository.findOne(addList.get(i).getActivityId());
//                        if (StringUtils.isNotEmpty(addList.get(i).getButtonName())) {
//                            activity.setButtonName(addList.get(i).getButtonName());
//                        }
//                        if (StringUtils.isNotEmpty(addList.get(i).getButtonImg())) {
//                            activity.setButtonImg(addList.get(i).getButtonImg());
//                        }
//                        activity.setUpdateTime(new Date());
//                        drawActivityRepository.saveAndFlush(activity);
//                    }
//                    ActivityModuleConfig entity = amcRepository.saveAndFlush(config);
//                    List<ActivityModuleConfigChild> lbtList = addList.get(i).getLbtList();
//                    cl = new ActivityModuleConfigChild();
//                    if(StringUtils.isNotEmpty(addList.get(i).getUrl())){
//                        cl.setUrl(addList.get(i).getUrl());
//                        cl.setActivityModuleConfigId(entity.getId());
//                        if(StringUtils.isNotEmpty(addList.get(i).getVideoImage())){
//                            cl.setVideoImage(addList.get(i).getVideoImage());
//                        }
//                        allList.add(cl);
//                    }else{
//                        if(lbtList !=null && lbtList.size() >0){
//                            for (ActivityModuleConfigChild child:lbtList) {
//                                child.setActivityModuleConfigId(entity.getId());
//                                child.setUrl(child.getUrl());
//                                allList.add(child);
//                            }
//                        }
//                    }
                    /**
                     * 引入addActivityModuleList，进行组件配置新增
                     */
//                    if(addList.get(i).getId() != null){
//                    if(StringUtils.isNotEmpty(addList.get(i).getActivityId())){
//                        //删除该活动原有组件
//                        amRepository.deleteByActivityId(addList.get(i).getActivityId());
//                    }
//                        ActivityModule activityModule = new ActivityModule();
//                        activityModule.setActivityId(addList.get(i).getActivityId());
//                        activityModule.setActivityModuleConfigId(addList.get(i).getId());
//                        long m =1;
//                        activityModule.setModuleOrder(m);
//                        amRepository.save(activityModule);
//                    }
                }
                }
                if (allList != null && allList.size() > 0) {
                amcchildRepository.save(allList);
                }
            }
            result.setState(0);
            result.setMessage("添加成功");
        }else{
            result.setState(-1);
            result.setMessage("参数异常!");
        }
        return result;
    }

  //查询所有组件
    public JsonResult findAllModule() {
        JsonResult result = new JsonResult();
        List<ActivityModuleConfig> list = amcRepository.findAll();
        Collections.sort(list, Comparator.comparing(ActivityModuleConfig::getId));
        if(list !=null && list.size() >0){
            List<ActivityModuleConfigVM> returnList =new ArrayList<>();
            ActivityModuleConfigVM vm =null;
            for (ActivityModuleConfig config:list ) {
                vm =new ActivityModuleConfigVM();
                List<ActivityModuleConfigChild> activityChildList = amcchildRepository.findByActivityModuleConfigId(config.getId());
                vm.setId(config.getId());
                vm.setComponentName(config.getComponentName());
                vm.setType(config.getType());
                if(activityChildList!=null && activityChildList.size() >0) {
                    if (config.getType() == 1) {
                        //轮播图
                        vm.setLbtList(activityChildList);
                        vm.setTitle("轮播图");
                        vm.setIsAutoLb(config.getIsAutoLb());
                    } else if (config.getType() == 2) {
                        //视频
                        vm.setVideoUrl(activityChildList.get(0).getUrl());
                        vm.setTitle("视频");
                        if(StringUtils.isNotEmpty(activityChildList.get(0).getVideoImage())){
                            vm.setVideoImage(activityChildList.get(0).getVideoImage());
                        }
                        vm.setActivityModuleConfigChildId(activityChildList.get(0).getId());
                    } else if (config.getType() == 3) {
                        //图片
                        vm.setImgUrl(activityChildList.get(0).getUrl());
                        vm.setTitle("图片");
                        vm.setActivityModuleConfigChildId(activityChildList.get(0).getId());
                    }
                }
                returnList.add(vm);
            }
            result.setData(returnList);
            result.setState(0);
        }
        return result;
    }

    public JsonResult addActivityModule(ActivityModule entity) {
        JsonResult result =new JsonResult();
        if(entity !=null){
            amRepository.saveAndFlush(entity);
            result.setMessage("活动组件模块配置完成");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult findModuleByActivityId(String activityId) {
        JsonResult result =new JsonResult();
        if(activityId !=null){
            List<ActivityModule> list = amRepository.findByActivityId(activityId);
            Collections.sort(list, Comparator.comparing(ActivityModule::getModuleOrder));
            List<ActivityModuleConfigVM> returnList =new ArrayList<>();
            if(list !=null && list.size() >0){
                ActivityModuleConfigVM vm =null;
                for (ActivityModule config:list ) {
                    if (config.getActivityModuleConfigId() != null) {
                        List<ActivityModuleConfigChild> activityChildList = amcchildRepository.findByActivityModuleConfigId(config.getActivityModuleConfigId());
                        ActivityModuleConfig con = amcRepository.findOne(config.getActivityModuleConfigId());
                        vm = new ActivityModuleConfigVM();
                        vm.setActivityId(activityId);
                        vm.setId(con.getId());
                        vm.setComponentName(con.getComponentName());
                        vm.setType(con.getType());
                        if (activityChildList != null && activityChildList.size() > 0) {
                            if (con != null) {
                                if (con.getType() == 1) {
                                    //轮播图
                                    vm.setIsAutoLb(con.getIsAutoLb());
                                    vm.setLbtList(activityChildList);
                                    vm.setTitle("轮播图");
                                } else if (con.getType() == 2) {
                                    //视频
                                    vm.setVideoUrl(activityChildList.get(0).getUrl());
                                    vm.setTitle("视频");
                                    vm.setUrl(activityChildList.get(0).getUrl());
                                    vm.setVideoImage(activityChildList.get(0).getVideoImage());
                                } else if (con.getType() == 3) {
                                    //图片
                                    vm.setImgUrl(activityChildList.get(0).getUrl());
                                    vm.setTitle("图片");
                                    vm.setUrl(activityChildList.get(0).getUrl());
                                }
                                vm.setType(con.getType());
                                vm.setId(con.getId());
                                returnList.add(vm);
                            }
                        }
                    }
                }
            }
            result.setData(returnList);
            result.setState(0);
        }else{
            result.setMessage("参数activityId不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult delete(ActivityModule entity) {
        JsonResult result =new JsonResult();
        amRepository.delete(entity.getId());
        result.setMessage("删除成功");
        result.setState(0);
        return result;
    }

    public JsonResult addActivityModuleList(ActivityModuleVM vm) {
        JsonResult result =new JsonResult();
        if(StringUtils.isNotEmpty(vm.getActivityId())){
            //删除该活动原有组件
            amRepository.deleteByActivityId(vm.getActivityId());
        }
        if(vm !=null && vm.getList().size() > 0){
            List<ActivityModule> list = vm.getList();
            if(list !=null && list.size() >0){
                long i =0;
                for (ActivityModule am:list) {
                    i+=1;
                    am.setModuleOrder(i);
                }
                amRepository.save(list);
            }
        }
        result.setMessage("操作成功");
        result.setState(0);
        return result;
    }

    public JsonResult deleteComponent(ActivityModuleConfigVM vm) {
        JsonResult result =new JsonResult();
        if(vm.getId() !=null){
            amcRepository.delete(vm.getId());
            amcchildRepository.deleteByActivityModuleConfigId(vm.getId());
            result.setMessage("操作成功");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空");
            result.setState(-1);
        }
        return result;
    }


    public JsonResult findById(Long id) {
        JsonResult result =new JsonResult();
        if(id !=null){
            ActivityModuleConfig con = amcRepository.findOne(id);
            List<ActivityModuleConfigChild> activityChildList = amcchildRepository.ActivityModuleConfigId(id);
            ActivityModuleConfigVM vm =new ActivityModuleConfigVM();
            if(activityChildList !=null && activityChildList.size() >0){
               if(con !=null){
                   if (con.getType() == 1) {
                       //轮播图
                       vm.setIsAutoLb(con.getIsAutoLb());
                       vm.setLbtList(activityChildList);
                       vm.setTitle("轮播图");
                   } else if (con.getType() == 2) {
                       //视频
                       vm.setVideoUrl(activityChildList.get(0).getUrl());
                       vm.setTitle("视频");
                       vm.setUrl(activityChildList.get(0).getUrl());
                       vm.setVideoImage(activityChildList.get(0).getVideoImage());
                   } else if (con.getType() == 3) {
                       //图片
                       vm.setImgUrl(activityChildList.get(0).getUrl());
                       vm.setTitle("图片");
                       vm.setUrl(activityChildList.get(0).getUrl());
                   }
                   vm.setType(con.getType());
                   vm.setComponentName(con.getComponentName());
               }
               result.setState(0);
               result.setData(vm);
            }
        }else{
            result.setMessage("参数不能为空");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult editCoupon(ActivityModuleConfigEditVM vm) {
        JsonResult result =new JsonResult();
        ActivityModuleConfig con = amcRepository.findOne(vm.getId());
        //如果修改了类型，删除原有子类
        if(con.getType() !=vm.getType()){
            amcchildRepository.deleteByActivityModuleConfigId(vm.getId());
            con.setType(vm.getType());
        }
        if (vm.getIsAutoLb()!=null) {
            con.setIsAutoLb(vm.getIsAutoLb());
        }
        con.setComponentName(vm.getComponentName());
        amcRepository.saveAndFlush(con);


        if (con.getType() == 1) {
            //轮播图
            List<Long> idList =new ArrayList<>();
            ActivityModuleConfigChild activityModule =null;
            List<ActivityModuleConfigChild> addList = new ArrayList<>();
            if(vm.getLbtList() !=null && vm.getLbtList().size() >0){
                List<ActivityModuleConfigChild> list = vm.getLbtList();
                for (int i =0;i <list.size() ;i ++ ) {
                    activityModule = new ActivityModuleConfigChild();
                    if(list.get(i).getId() !=null){
                        activityModule.setId(list.get(i).getId());
                        idList.add(list.get(i).getId());
                    }
                    if(vm.getId()!=null){
                        activityModule.setActivityModuleConfigId(vm.getId());
                    }
                    if(StringUtils.isNotEmpty(vm.getVideoImage())){
                        activityModule.setVideoImage(vm.getVideoImage());
                    }
                    activityModule.setUrl(list.get(i).getUrl());
                    addList.add(activityModule);
                }
            }
            //            List<Long> idList =new ArrayList<>();
//            ActivityModule activityModule =null;
//            List<ActivityModule> addList = new ArrayList<>();
//            for (int i =0;i <list.size() ;i ++ ) {
//                activityModule = new ActivityModule();
//                if(list.get(i).getId() !=null){
//                    activityModule.setId(list.get(i).getId());
//                    idList.add(list.get(i).getId());
//                }
//                if(StringUtils.isNotEmpty(list.get(i).getActivityId())){
//                    activityModule.setActivityId(list.get(i).getActivityId());
//                }
//                if(list.get(i).getActivityModuleConfigId()!=null){
//                    activityModule.setActivityModuleConfigId(list.get(i).getActivityModuleConfigId());
//                }
//                long b = i+1;
//                activityModule.setModuleOrder(b);
//                addList.add(activityModule);
//            }
//            if(idList.size() >0){
//                amRepository.deleteByCondition(idList,vm.getActivityId());
//           }
            if(idList.size() >0){
                amcchildRepository.deleteByCondition(idList,vm.getId());
           }
            amcchildRepository.save(addList);
        } else{
            //视频或者图片
            ActivityModuleConfigChild configChild = new ActivityModuleConfigChild();
            if(vm.getActivityModuleConfigChildId()!=null){
                configChild.setId(vm.getActivityModuleConfigChildId());
            }
            if(StringUtils.isNotEmpty(vm.getVideoImage())){
                configChild.setVideoImage(vm.getVideoImage());
            }
            if(vm.getId()!=null){
                configChild.setActivityModuleConfigId(vm.getId());
            }
            configChild.setUrl(vm.getUrl());
            amcchildRepository.saveAndFlush(configChild);
        }
        result.setMessage("编辑成功");
        result.setState(0);
        return result;
    }

    /**
     * 210809 18:32:35
     * @param componentName
     * @return
     */
    public List<ActivityModuleConfigDTO> findByLikecomponentName(String componentName) {
        if (StringUtils.isNotBlank(componentName)){
            ActivityModuleConfig byComponentName = amcRepository.findByComponentName(componentName);
            List<ActivityModuleConfigDTO> qrCodeDTOStream = null;
            if (byComponentName != null){
                    List<ActivityModuleConfigVM> returnLists = new ArrayList<>();
                    ActivityModuleConfigVM vm =null;
                        vm =new ActivityModuleConfigVM();
                        List<ActivityModuleConfigChild> activityChildList = amcchildRepository.findByActivityModuleConfigId(byComponentName.getId());
                        vm.setId(byComponentName.getId());
                        vm.setComponentName(byComponentName.getComponentName());
                        vm.setType(byComponentName.getType());
                        if(activityChildList!=null && activityChildList.size() >0) {
                            if (byComponentName.getType() == 1) {
                                //轮播图
                                vm.setLbtList(activityChildList);
                                vm.setTitle("轮播图");
                                vm.setIsAutoLb(byComponentName.getIsAutoLb());
                            } else if (byComponentName.getType() == 2) {
                                //视频
                                vm.setVideoUrl(activityChildList.get(0).getUrl());
                                vm.setTitle("视频");
                                if (StringUtils.isNotEmpty(activityChildList.get(0).getVideoImage())) {
                                    vm.setVideoImage(activityChildList.get(0).getVideoImage());
                                }
                                vm.setActivityModuleConfigChildId(activityChildList.get(0).getId());
                            } else if (byComponentName.getType() == 3) {
                                //图片
                                vm.setImgUrl(activityChildList.get(0).getUrl());
                                vm.setTitle("图片");
                                vm.setActivityModuleConfigChildId(activityChildList.get(0).getId());
                            }
                            returnLists.add(vm);
                        }
                        qrCodeDTOStream = returnLists.stream().map(returnList -> this.toActivityModuleConfigVM(returnList)).collect(Collectors.toList());
                        return qrCodeDTOStream;

            }
            return qrCodeDTOStream;
//            else {
//                List<ActivityModuleConfig> configLists = amcRepository.findByComponentNameLike(componentName);
//                List<ActivityModuleConfigDTO> qrCodeDTOStream = configLists.stream().map(configList -> this.toActivityModuleConfigDTO(configList)).collect(Collectors.toList());
//                return qrCodeDTOStream;
//                }
        }
//        else {
//            List<ActivityModuleConfig> configLists = amcRepository.findAll();
//            List<ActivityModuleConfigDTO> qrCodeDTOStream = configLists.stream().map(configList -> this.toActivityModuleConfigDTO(configList)).collect(Collectors.toList());
//            return qrCodeDTOStream;
//        }
            return null;
    }

    private ActivityModuleConfigDTO toActivityModuleConfigDTO(ActivityModuleConfig config) {
        ActivityModuleConfigDTO dto = new ActivityModuleConfigDTO();
        BeanUtils.copyProperties(config, dto);
        return dto;
    }
    private ActivityModuleConfigDTO toActivityModuleConfigVM(ActivityModuleConfigVM config) {
        ActivityModuleConfigDTO dto = new ActivityModuleConfigDTO();
        BeanUtils.copyProperties(config, dto);
        return dto;
    }
}
